#!/usr/bin/env bash
#=======================================================================#
# Copyright (C) 2020 - 2024 Dominik Willner <th33xitus@gmail.com>       #
#                                                                       #
# This file is part of KIAUH - Klipper Installation And Update Helper   #
# https://gitee.com/longhuohuxiao/kiauh                                 #
#                                                                       #
# This file may be distributed under the terms of the GNU GPLv3 license #
#=======================================================================#
#===================================================#
#================ INSTALL SHAKETUNE ================#
#===================================================#

function patch_timelapse_config() {
  local patched moonraker_configs regex
  regex="${HOME//\//\\/}\/([A-Za-z0-9_]+)\/config\/moonraker\.conf"
  moonraker_configs=$(find "${HOME}" -maxdepth 3 -type f -regextype posix-extended -regex "${regex}" | sort)

  patched="false"
  for conf in ${moonraker_configs}; do
    if ! grep -Eq "^\[timelapse]\s*$" "${conf}"; then
      ### add new line to conf if it doesn't end with one
      [[ $(tail -c1 "${conf}" | wc -l) -eq 0 ]] && echo "" >> "${conf}"

      ### add Fluidds update manager section to moonraker.conf
      status_msg "Adding Fluidd to update manager in file:\n       ${conf}"
      /bin/sh -c "cat >> ${conf}" << MOONRAKER_CONF

[timelapse]
output_path: ~/printer_data/timelapse/
frame_path: ~/timelapse_tmp/
MOONRAKER_CONF

    fi

    patched="true"
  done

  if [[ ${patched} == "true" ]]; then
    do_action_service "restart" "moonraker"
  fi
}

function install_timelapse() {
    echo "正在克隆 TIMELAPSE 仓库到 ${HOME} ..."
    cd ${HOME} && git clone ${TIMELAPSE_REPO}
    echo "克隆完成！"
    # 运行 install.sh
    echo "正在运行安装脚本..."
    bash -c ${TIMELAPSE_DIR}/scripts/install.sh
    patch_timelapse_config
} 
